package com.lhkj.ct.framework.filter;

import com.lhkj.ct.framework.shiro.session.ShiroSessionManager;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * CookieFilter
 */
//@WebFilter(urlPatterns = "/*", filterName = "cookieFilter")
public class CookieFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
//        this.xtszService = SpringContextHolder.getBean(XTSZServiceImpl.class);
    }


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        String projectName = req.getServletContext().getContextPath();
        Cookie[] cookies = req.getCookies();
        if (cookies != null) {
            Cookie cookie = Arrays.stream(cookies).filter(c -> c.getName().equals(ShiroSessionManager.HEADER_TOKEN_NAME)).findFirst().orElse(null);
            if (cookie != null) {
                String value = cookie.getValue();
                StringBuilder builder = new StringBuilder();
                builder.append(ShiroSessionManager.HEADER_TOKEN_NAME).append("=").append(value).append(";");
                builder.append("path=").append(projectName).append(";");
                if (req.getScheme().equalsIgnoreCase("https")) {
                    builder.append("secure;");
                }
                builder.append("HttpOnly;");
                resp.setHeader("Set-Cookie", builder.toString());
            }
        }
        filterChain.doFilter(servletRequest, resp);
    }

    @Override
    public void destroy() {

    }
}
